<template>
  <div id="shop-manage">

    <div class="search-box">
        <el-form>
             <el-form-item label="店铺名称：">
                <el-select v-model="searchForm.shopName" placeholder="请选择店铺" size="small" filterable :filter-method="dataFilter" clearable>
                  <el-option v-for="(item, index) in shopNameList" :key="index" :label="item.name" :value="item.name"></el-option>
                </el-select>
             </el-form-item>
            <el-form-item>
                <el-button class="search-btn" icon="el-icon-ali-search" @click="searchData()">查&nbsp;询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div class="table-box">
      <div class="add-shop-box">
        <el-button class="add-btn" icon="el-icon-plus" @click="showAddDialog">添加店铺</el-button>
        <div class="tips">店铺可以直接添加，余额不足不能添加店铺哦。没有授权的店铺，将不会进行自动审核订单。如果需要授权店铺，请联系客服。</div>
      </div>
      <el-table border :data="shopList" max-height="580px">
        <el-table-column prop="type" :formatter="getPlantformType" label="平台"></el-table-column>
        <el-table-column prop="group_name"  label="店铺分组"></el-table-column>
        <el-table-column prop="name"  label="店铺名称"></el-table-column>
        <el-table-column prop="shop_url"  label="店铺链接">
          <div slot-scope="scope">
            <div class="look-btn" @click="toShopUrl(scope.row)" v-if="scope.row.shop_url">查看</div>
          </div>
        </el-table-column>
        <el-table-column prop="bind_status" :formatter="getBindStatus" label="自动审核订单"></el-table-column>
        <el-table-column label="操作">
      		<template slot-scope="scope">
            <el-button class="opt-btn" @click="tableShopAuto(scope.row)" v-if="scope.row.auth_flag_type ==2">授权</el-button>
            <el-button class="opt-btn btn-color-4" @click="flagShop(scope.row)" v-if="scope.row.auth_flag_type == 2 || scope.row.auth_flag_type == 3">标旗</el-button>
      		</template>
      	</el-table-column>
      </el-table>
      <el-table  border id="tabledata" :data="allShopList" v-show="false">
        <el-table-column prop="type" :formatter="getPlantformType" label="平台"></el-table-column>
        <el-table-column prop="group_name"  label="店铺分组"></el-table-column>
        <el-table-column prop="name"  label="店铺名称"></el-table-column>
        <el-table-column prop="shop_url"  label="店铺链接"></el-table-column>
        <el-table-column prop="bind_status" :formatter="getBindStatus" label="自动审核订单"></el-table-column>

      </el-table>
      <div class="table-footer">
        <el-button icon="el-icon-download" class="download-btn" @click="downloadExcel">导出</el-button>
        <div>
          <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="searchForm.pageSize" :current-page="searchForm.page" layout="total, sizes, prev, pager, next, jumper"
            :total="allNum" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="添加店铺" :visible.sync="isShowAddDialog" width="400px" class="dialog-style add-dialog">
      <el-form>
        <el-form-item label="平台类型:">
          <el-select v-model="bindShopForm.shopType" placeholder="平台类型" size="small">
           <el-option v-for="(item,index) in shopCheckList" :key="index" :label="item.label"
             :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺名称:">
          <el-input v-model="bindShopForm.shopName" size="small" clearable placeholder="请输入店铺名称"></el-input>
        </el-form-item>
        <el-form-item label="店铺链接:">
          <el-input v-model="bindShopForm.shopUrl" size="small" maxlength="1000" clearable placeholder="请输入店铺链接"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddDialog = false" class="cancel-btn">取 消</el-button>
        <el-button  @click="submitShop" :loading="bindLoading" :disabled="bindLoading" class="submit-btn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="标旗" :visible.sync="isShowFlagDialog"  width="500px" class="dialog-style flag-dialog" style="height: 700px;">
        <div>
          <div class="radio-list">
            <span class="title">标记：</span>
            <el-radio-group v-model="flagForm.flagType">
                <el-radio :label="1"><img class="flag-img" src="../../assets/image/flag-1.png" alt=""></el-radio>
                <el-radio :label="2"><img class="flag-img" src="../../assets/image/flag-2.png" alt=""></el-radio>
                <el-radio :label="3"><img class="flag-img" src="../../assets/image/flag-3.png" alt=""></el-radio>
                <el-radio :label="4"><img class="flag-img" src="../../assets/image/flag-4.png" alt=""></el-radio>
                <el-radio :label="5"><img class="flag-img" src="../../assets/image/flag-5.png" alt=""></el-radio>
                <el-radio :label="6"><span style="color:red">取消标旗</span></el-radio>
              </el-radio-group>
          </div>
          <div>
            <span class="title">备注：</span>
            <el-input type="textarea" :rows="5" class="remark-textarea" v-model="flagForm.flagRemark"></el-input>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancel-btn" @click="isShowFlagDialog = false">取消</el-button>
          <el-button class="submit-btn" :loading="flagLoading" :disabled="flagLoading" @click="submitFlag">确认</el-button>
        </div>
    </el-dialog>
    <el-dialog title="店铺授权" :visible.sync="isShowShopAutoDialog"  width="500px" class="dialog-style auth-dialog">
        <div class="autho-box">
          <div class="left-box">
            <div class="num">1</div>
            <div class="line"></div>
          </div>
          <div class="right-box">
            <div class="title-1">去完成订购（<b>订购一年显示128元，实付0.01元</b>）</div>
            <div class="title-2">请使用需要授权的淘宝店铺登录进行订购</div>
            <div class="auto-btn" @click="shopOrder">订购</div>
          </div>
        </div>

        <div class="autho-box">
          <div class="left-box">
            <div class="num">2</div>
            <div class="line"></div>
          </div>
          <div class="right-box">
             <div class="title-1">登录淘宝店铺进行授权</div>
             <div class="title-2">请使用需要授权的淘宝店铺登录</div>
             <div class="auto-btn" @click="shopAuto">授权</div>
          </div>
        </div>

        <div class="autho-box">
          <div class="left-box">
            <div class="num">3</div>
          </div>
          <div class="right-box">
            <span>请输入淘宝userid:</span>
            <el-input class="input" v-model="shopAutoForm.taobaoUserId" size="small" clearable placeholder="请输入淘宝userid"></el-input>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancel-btn" @click="isShowShopAutoDialog = false">取消</el-button>
          <el-button class="submit-btn" :loading="shopAuthLoading" :disabled="shopAuthLoading" @click="submitShopAuth">确认</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    apiGetMerchantShopList,
    apiMerchantShop,
    apiShopAuthConfig,
    apiBindShop,
    apiShopFlagSetting,
    apiShopAuth
  } from '../../request/api.js'
  import { mapGetters,mapActions } from 'vuex';
  export default{
    data(){
      return {
          searchForm:{
            token: '',
            shopName: '',
            page: 1,
            pageSize: 10
          },
          shopNameList: [],
          shopNameOptions: [],
          shopList: [],
          allShopList: [],
          flagForm:{
            shopId: '',
            token: '',
            flagRemark: '',
            flagType: null
          },
          bindType: {
            1: '自动',
            2: '其他'
          },
          platformType:{
            1: '淘宝',
            2: '天猫',
            3: '京东',
            4: '1688',
            13: '唯品会',
            15: '拼多多'
          },
          bindStatus:{
            1: '是',
            2: '否'
          },
          shopShowType: window.localStorage.getItem('shopShowType'),
          shopCheckList: [],
          shopUrl: '',
          platformTypeList: [{
            label: '淘宝',
            value: 1
          },{
            label: '天猫',
            value: 2
          },{
            label: '京东',
            value: 3
          },{
            label: '1688',
            value: 4
          },{
            label: '唯品会',
            value: 13
          },{
            label: '拼多多',
            value: 15
          }],
          allNum: 0,
          buyUrl: '',
          authUrl: '',
          bindShopForm:{
            token: '',
            shopType: '',
            shopName: '',
            shopUrl: ''
          },
          bindLoading: false,
          isShowAddDialog: false,
          isShowFlagDialog: false,
          flagLoading: false,
          shopAuthLoading: false,
          isShowShopAutoDialog: false,
          isClickAuto: false,
          isClickOrder: false,
          shopAutoForm:{
            token: '',
            shopId: '',
            taobaoUserId: ''
          },
          userToken: window.localStorage.getItem('token'),
		  merchantData: JSON.parse(window.localStorage.getItem('merchantConfig')),
      }
    },
    created() {
      if(this.merchantData.shop_show_type){
        let shopShowTypeArr = this.merchantData.shop_show_type.split(',')
        for(var i in this.platformTypeList){
          if(shopShowTypeArr.indexOf(this.platformTypeList[i].value.toString()) >=0) {
            this.shopCheckList.push(this.platformTypeList[i])
          }
        }
      } else {
        this.shopCheckList = this.platformTypeList
      }
      this.getInitData();
      this.getShopAuthConfig()
      this.getShopList()
    },
    methods:{
       ...mapActions(['setShopNameList']),
      getInitData() {
        this.searchForm.token = this.userToken
        this.$isClick(true);
        apiMerchantShop(this.searchForm).then(res =>{
          this.$isClick(false);
           if (res.code == 1){
             this.shopList = res.msg.merchant_shop_list;
             this.allNum = res.msg.all_num
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
          this.$isClick(false);
            this.$message.error(res.msg)
        })
      },
      getShopAuthConfig() {
        this.$isClick(true);
        apiShopAuthConfig({
          token: this.userToken
        }).then(res =>{
          this.$isClick(false);
           if (res.code == 1){
            this.buyUrl = res.msg.buyUrl
            this.authUrl = res.msg.authUrl
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
          this.$isClick(false);
            this.$message.error(res.msg)
        })
      },
      toShopUrl(row){
        window.open(row.shop_url,'shopUrl')
      },
      //店铺下拉框搜索
      dataFilter(val) {
        this.searchForm.shopName = val;
        if (val) { //val存在
          this.shopNameList = this.shopNameOptions.filter((item) => {
            if (!!~item.name.indexOf(val) || !!~item.name.toUpperCase().indexOf(val.toUpperCase())) {
              return true
            }
          })
        } else { //val为空时，还原数组
          this.shopNameList = this.shopNameOptions;
        }
      },
      //获取店铺名称
      getShopList() {
        this.$isClick(true);
        apiGetMerchantShopList({
          token: this.userToken
        }).then(res =>{
          this.$isClick(false);
           if (res.code == 1){
             for (var i in res.msg.merchant_shop_list) {
               this.shopNameList.push({
                 name: res.msg.merchant_shop_list[i].name,
                 id: res.msg.merchant_shop_list[i].id
               })
             }
             this.shopNameOptions = this.shopNameList
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
          this.$isClick(false);
            this.$message.error(res.msg)
        })
      },
      getBindStatus(row){
        return this.bindStatus[row.bind_status]
      },
      getBindType(row){
       return this.bindType[row.bind_type]
      },
      getPlantformType(row){
       return this.platformType[row.type]
      },
      flagShop(row){
        this.isShowFlagDialog = true
        this.flagForm = {
          shopId: row.id,
          token: this.userToken,
          flagRemark: row.flag_remark ? row.flag_remark : null,
          flagType: row.flag_type ? row.flag_type : null
        }
      },
      tableShopAuto(row){
        this.isShowShopAutoDialog = true
        this.shopAutoForm.token = this.userToken
        this.shopAutoForm.shopId = row.id
        this.shopAutoForm.taobaoUserId = ''
        this.isClickAuto = false
        this.isClickOrder = false
      },
      shopOrder(){
        this.isClickOrder = true
        window.open(this.buyUrl, 'buyUrl');
      },
      shopAuto(){
         this.isClickAuto = true
         //window.open(this.authUrl, 'authUrl');
         window.open(this.authUrl+"%26shopId%3d"+this.shopAutoForm.shopId, 'authUrl');
      },
      submitShopAuth(){
        if(!this.shopAutoForm.taobaoUserId){
          this.$message.error('请先输入userId')
          return
        }
        if(!this.isClickOrder){
          this.$message.error('请先订购店铺')
          return
        }
        if(!this.isClickAuto){
          this.$message.error('请先授权店铺')
          return
        }
        this.shopAuthLoading = true
        apiShopAuth(this.shopAutoForm).then(res =>{
            this.shopAuthLoading = false
            this.isClickAuto = false
            this.isClickOrder = false
           if (res.code == 1){
             this.$message.success(res.msg);
             this.isShowShopAutoDialog = false
             this.getInitData()
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
           this.shopAuthLoading = false
           this.$message.error(res.msg)
        })
      },
      handleSizeChange(val) {
        this.searchForm.pageSize = val;
        this.getInitData();
      },
      handleCurrentChange(val) {
        this.searchForm.page = val;
        this.getInitData();
      },
      showAddDialog(){
        if(this.merchantData.add_shop == 1) {
          this.bindShopForm = {
            token: this.userToken,
            shopType: '',
            shopName: '',
            shopUrl: ''
          }
          this.isShowAddDialog = true
        } else {
          this.$message.error('店铺已饱和，如果需要继续添加请联系管理员');
        }

      },
      submitShop(){
        if (!this.bindShopForm.shopType) {
          this.$message.error('请先选择平台类型')
          return
        }
        if (!this.bindShopForm.shopName) {
          this.$message.error('店铺名称不能为空！')
          return
        }
        if (this.bindShopForm.shopName.length<=3 && this.bindShopForm.shopName.indexOf(' ')>= 0) {
          this.$message.error('店铺名称格式不对！')
          return
        }
        if (!this.bindShopForm.shopUrl) {
          this.$message.error('店铺链接不能为空！')
          return
        }
        this.bindLoading = true
        apiBindShop(this.bindShopForm).then(res =>{
            this.bindLoading = false
           if (res.code == 1){
             this.$message.success(res.msg);
             this.isShowAddDialog = false
             this.getInitData()
             this.setShopNameList()
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
           this.bindLoading = false
           this.$message.error(res.msg)
        })
      },
      submitFlag(){
        if(!this.flagForm.flagType){
          this.$message.error('请先选择标记')
          return
        }
        this.flagLoading = true
        apiShopFlagSetting(this.flagForm).then(res =>{
           this.flagLoading = false
           if (res.code == 1){
            this.$message.success(res.msg);
            this.isShowFlagDialog = false
            this.getInitData();
           } else {
             this.$message.error(res.msg);
           }
        }).catch(res => {
            this.flagLoading = false
            this.$message.error(res.msg)
        })
      },
      searchData(){
        this.searchForm.page = 1
        this.searchForm.pageSize = 10
        this.getInitData()
      },
      getAllTableData(){
        let data = JSON.parse(JSON.stringify(this.searchForm))
        data.page = 1
        data.pageSize = this.allNum
        if (data.pageSize == 0) {
           this.$message.error('当前表格没有数据可以导出');
           return
        }
        return new Promise ((resolve) =>{
          this.$isClick(true);
          apiMerchantShop(data).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
               this.allShopList = res.msg.merchant_shop_list;
               resolve(res) ;
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
        })

      },
      downloadExcel(){
        this.$loading.show('下载中')
        var wb = ''
         var xlsxParam = { raw: true }
         this.getAllTableData().then(()=>{
         wb = this.XLSX.utils.table_to_book(document.querySelector('#tabledata'),xlsxParam)
         var wbout = this.XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
         try {
           this.FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }),'店铺信息.xlsx')
         } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
         setTimeout(() => {
           this.$loading.hide()
           this.$message.success('下载完成')
         }, 1000);
         return wbout
        })
      }
    }
  }
</script>

<style lang="less">
  #shop-manage {
    .add-shop-box {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
      background: #FFFFFF;
      .add-btn {
        height: 32px !important;
        padding: 0px 10px !important;
        background: @themeColor;
        color: #ffffff;
      }
      .tips{
        font-size: 14px;
        margin-left: 10px;
        color: #666666;
      }
    }
    .table-box {
      .look-btn {
        height: 28px !important;
        padding: 0px 15px !important;
        background: #ff5001;
        color: #ffffff;
        display: inline-block;
        line-height: 28px;
        border-radius: 3px;
        font-size: 14px;
        cursor: pointer;
      }
    }
    .dialog-style {
      &.add-dialog{
        .el-dialog {
          height: 360px;
        }
      }
      &.flag-dialog{
        .el-dialog {
          height: 360px;
        }
      }
      &.auth-dialog {
        .el-dialog {
          height: 475px;
        }
        .autho-box {
          display: flex;
          .left-box {
            .num {
              width: 20px;
              height: 20px;
              background: red;
              color: #FFFFFF;
              border-radius: 50%;
              text-align: center;
              line-height: 20px;
            }
            .line {
              width: 1px;
              height: 100px;
              background: red;
              margin-left: 9px;
            }
          }
          .right-box {
            margin-left: 20px;
            .title-1 {
              color: #888888;

              b {
                color: red;
              }
            }
            .title-2 {
              color: red;
              margin: 8px 0;
            }
            .auto-btn {
              background: red;
              display: inline-block;
              color: #FFFFFF;
              padding: 5px 10px;
              border-radius: 3px;
              cursor: pointer;
            }
            .input {
              margin-top: 10px;
              width: 200px;
              display: block;
            }
          }
        }
      }
      .radio-list {
        margin-bottom: 20px;

        .el-radio {
          margin-right: 16px;
        }
        .title {
          display: inline-block;
          vertical-align: sub;
        }
        .el-radio__label {
          padding-left: 5px!important;
        }
        .flag-img {
          width: 23px;
          height: 23px;
          display: inline-block;
          vertical-align: bottom;
        }
      }
    }
  }
</style>
